package com.zdp.common.handler;

import com.zdp.common.domain.ResultInfo;
import com.zdp.common.exception.GlobalException;
import com.zdp.common.util.ResultInfoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * @author sesshomaru
 * @date 2021/7/30
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的GlobalException异常
     * @param ex
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultInfo<Map<String, String>> handlerGlobalException(GlobalException ex) {
        logger.error("GlobalException error:", ex);
        return ResultInfoUtil.buildError(ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 处理未知的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultInfo<Map<String, String>> handlerException(Exception ex) {
        logger.error("未知异常：{}", ex.getMessage());
        // 打印异常的实际堆栈信息
        ex.printStackTrace();
        return ResultInfoUtil.buildError();
    }
}
